<template>
  <div class="app-container">
    <!-- 系统通知-我的消息 -->
    <div class="none2-border3 messagelist mainbox">
      <div class="filter-container">
        <el-form ref="filterFormRef" :model="filterForm" :inline="true"
                 @submit.native.prevent>
          <el-form-item label="消息标题" prop="messageTitle">
            <el-input v-model.trim="filterForm.messageTitle" maxlength="30" clearable
                      placeholder="请输入内容" class="filter-item limit" @keyup.enter.native="query" />
          </el-form-item>
          <el-form-item label="消息类型" prop="messageType">
            <el-select v-model="filterForm.messageType" placeholder="请选择" clearable
                       size="small">
              <el-option
                v-for="messageType in messageTypeList"
                :key="messageType.typeId"
                :label="messageType.typeName"
                :value="messageType.typeId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="flex-1" />
        <el-button type="primary" icon="el-icon-search" @click="query"> 搜索</el-button>
        <el-button @click="handleReset"> 重置</el-button>
      </div>
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <!-- <el-button v-permission="['NOTICE_FIND_READALL_BUTTON']" type="primary" @click="AllRead"> 全部已读</el-button> -->
          <!-- <el-button v-permission="['NOTICE_FIND_OUT_BUTTON']" type="" :disabled="tableData.length<=0" @click="exported"> 导出</el-button> -->
          <div class="flex-1" />
          <dt-dialog-column :columns="columns" @queryTable="getList" />
        </div>
        <el-table
          ref="table"
          v-loading="loading"
          :data="tableData"
          highlight-current-row
          :header-cell-style="headerCellStyle"
          row-key="messageId"
          border
          @selection-change="handleSelectionChange"
        >
          <template slot="empty">
            <p>{{ $store.getters.dataText }}</p>
          </template>
          <!-- <el-table-column
            type="selection"
            min-width="80"
            :reserve-selection="true"
          /> -->
          <el-table-column
            fixed="left"
            type="index"
            label="序号"
            width="70"
            :index="table_index"
          />
          <el-table-column
            v-if="columns[0].show"
            key="messageTitle"
            prop="messageTitle"
            label="消息标题"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columns[1].show"
            key="messageContent"
            prop="messageContent"
            label="消息内容"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columns[2].show"
            key="messageType"
            prop="messageType"
            label="消息类型"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columns[3].show"
            key="sender"
            prop="sender"
            label="发送方"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columns[4].show"
            key="priorityLevel"
            prop="priorityLevel"
            label="优先级"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <dt-dict-tag :options="dict.type.classifyLevel" :value="scope.row.priorityLevel" />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columns[5].show"
            key="readFlag"
            prop="readFlag"
            label="阅读状态"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <dt-dict-tag :options="dict.type.readFlag" :value="scope.row.readFlag" />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columns[6].show"
            key="realSendTime"
            prop="realSendTime"
            label="发送时间"
            show-overflow-tooltip
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.realSendTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :key="Math.random()"
            label="操作"
            align="center"
            fixed="right"
            width="94px"
          >
            <template slot-scope="scope">
              <el-button v-permission="['NOTICE_FIND_DETAIL_BUTTON']" size="small" @click="handEdit(scope.row)">详情</el-button>
              <!-- <el-button v-permission="['NOTICE_FIND_DEL_BUTTON']" size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <dt-pagination
          v-show="total > 0"
          :total="total"
          :page.sync="filterForm.pageNo"
          :limit.sync="filterForm.pageSize"
          @pagination="getList"
        />
      </div>
      <!-- 查看 -->
      <dtDialog
        title="查看信息"
        :visible.sync="addVisible"
        :footer-slot="true"
      >
        <el-form
          ref="ruleForm"
          slot="content"
          :model="ruleForm"
          label-position="right"
          label-width="72px"
          disabled
        >
          <el-form-item label="消息标题" prop="messageTitle">
            <el-input v-model="ruleForm.messageTitle" type="textarea" autosize />
          </el-form-item>
          <el-form-item label="消息内容" prop="messageContent">
            <el-input v-model="ruleForm.messageContent" type="textarea" autosize
                      class="limit" />
          </el-form-item>
          <el-form-item label="消息类型" prop="messageType">
            <el-select v-model="ruleForm.messageType" style="width:100%">
              <el-option
                v-for="messageType in messageTypeList"
                :key="messageType.typeId"
                :label="messageType.typeName"
                :value="messageType.typeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="优先级" prop="priorityLevel">
            <el-select v-model="ruleForm.priorityLevel" style="width:100%">
              <el-option
                v-for="dict in dict.type.classifyLevel"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发送方" prop="sender">
            <el-input v-model="ruleForm.sender" />
          </el-form-item>

        </el-form>
      </dtDialog>
      <!-- 详情弹框 -->
      <dt-detail ref="dtDetailRef" :dt-detail-option="detailOption" />
    </div>
  </div>
</template>

<script>
import {
  getPageList,
  getAllReadList,
  getReadDetail,
  getDeleteRead,
  yesOrNotUnReadMessage,
  sysMessageExport,
  getMessageType } from '@/framework/api/message'
import dialogColumn from '@/framework/utils/mixins/dialogColumn'

export default {
  name: 'NoticeFind',
  dicts: ['messageType', 'readFlag', 'classifyLevel'],
  mixins: [dialogColumn],
  data() {
    return {
      messageTypeList: [],
      headerCellStyle: {
        backgroundColor: '#f2f2f2'
      },
      filterForm: {
        messageTitle: '',
        messageType: '',
        pageNo: 1,
        pageSize: 10
      },
      loading: false,
      // 弹框信息
      title: '新增公告',
      // 多选数组
      multipleSelection: [],
      // 列表数据
      tableData: [],
      total: 0,
      ruleForm: {},
      // 添加修改弹框
      addVisible: false,
      messageListLength: 0,
      // 列信息
      columns: [
        { prop: 'messageTitle', label: '消息标题', show: true },
        { prop: 'messageContent', label: '消息内容', show: true },
        { prop: 'messageType', label: '消息类型', show: true },
        { prop: 'sender', label: '发送方', show: true },
        { prop: 'priorityLevel', label: '优先级', show: true },
        { prop: 'readFlag', label: '阅读状态', show: true },
        { prop: 'realSendTime', label: '发送时间', show: true }

        // { prop: 'readFlagValue', label: `阅读状态`, show: true,fixed:true,sortable:true },
        // { prop: 'messageSendTime', label: `通知时间`, show: true }
      ]

    }
  },
  computed: {
    // 详情参数
    detailOption() {
      return {
        rows: [
          {
            label: '消息标题',
            prop: 'messageTitle'

          },
          {
            label: '消息内容',
            prop: 'messageContent'

          },
          {
            type: 'dict',
            options: this.dict.type.messageType,
            label: '消息类型',
            prop: 'messageType'

          },
          {
            label: '优先级',
            prop: 'priorityLevel'

          },
          // {
          //   label: '发送时间',
          //   prop: 'realSendTime'

          // },
          {
            label: '发送方',
            prop: 'sender'

          }
          // {
          //   label: '阅读状态：0-未读，1-已读',
          //   prop: 'readFlag'

          // },
        ],
        data: {}
      }
    }
  },
  mounted() {
    this.query()
    this.getMessageType()
  },
  methods: {
    getMessageType() {
      getMessageType().then((res) => {
        this.messageTypeList = res.data
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handEdit(row) {
      this.ruleForm = {}
      this.addVisible = true
      this.getDetail(row.messageId)
    },
    handleDelete(row) {
      this.$dtMessageBox({ title: '提示', message: '此操作将永久删除该消息, 是否继续?', type: 'warning' }).then(() => {
        getDeleteRead(row).then((res) => {
          this.$dtMessage({
            type: 'success',
            message: '删除成功'
          })
          this.multipleSelection.forEach((item, index) => {
            if (item.messageId === row.messageId) {
              this.multipleSelection.splice(index, 1)
            }
          })
          this.getList()
        })
      }).catch(() => {
      })
    },
    // 搜索
    query() {
      this.$refs.table.clearSelection()
      this.filterForm.pageNo = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.$refs.filterFormRef.resetFields()
      this.query()
    },
    resetForm() {
      this.addVisible = false
    },
    getList() {
      this.loading = true
      getPageList(this.filterForm).then((res) => {
        if (res.success === true) {
          this.loading = false
          this.total = res.data.totalRows
          this.total = res.data.totalRows
          this.tableData = res.data.rows
          this.messageListLength = res.data.rows.length
          // this.$forceUpdate()
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getDetail(id) {
      getReadDetail({
        messageId: id
      }).then((res) => {
        if (res.code === '00000') {
          // var l = res.data.messageContent.split('').length
          // var content = ''
          // res.data.messageContent.split('').forEach((element, index) => {
          //   if (index > 2 && index < l - 4) {
          //     content += element
          //   }
          // })
          // setTimeout(() => {
          this.ruleForm = res.data
          // this.ruleForm.messageContent = content
          // }, 50)
          this.getList()
          this.initUnReadMessage()
        }
      })
    },
    AllRead() {
      getAllReadList().then((res) => {
        if (res.code === '00000') {
          this.$dtMessage({
            type: 'success',
            message: '操作成功'
          })
          this.getList()
          this.initUnReadMessage()
        }
      })
    },
    initUnReadMessage() {
      yesOrNotUnReadMessage()
        .then((res) => {
          this.$store.dispatch('websocket/setIsUnReadMessage', res.data)
        })
    },
    exported() {
      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        this.$dtMessage({
          title: '失败',
          message: '请至少选择一项',
          type: 'error',
          duration: 2000
        })
        return
      }
      const messageIds = this.multipleSelection.map((res) => {
        return res.messageId
      }).join(',')
      this.$confirm('是否导出我的消息数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const con = {
          messageIds
        }
        this.downloadLoading = true
        sysMessageExport(con).then((res) => {
          this.dealBlob(res.data)
          this.query()
        })
      })
    },
    dealBlob(data) {
      const blob = new Blob([data], {
        // type: 'application/vnd.ms-excel'
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      const objectUrl = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.style.display = 'none' // 未点击前隐藏a链接
      a.href = objectUrl // 指定下载链接
      a.download = '我的消息导出' // 指定下载文件名
      a.click() // 触发a标签点击事件
      URL.revokeObjectURL(a.href) // 释放URL对象(从dom中移除该a链接)
      this.downloadLoading = false

      // import('@/framework/vendor/Export2Excel').then(excel => {
      //   const tHeader = ['业务类型', '消息标题', '优先级', '阅读状态', '收到时间']
      //   const filterVal = ['businessType', 'messageTitle', 'priorityLevelValue', 'readFlag', 'messageSendTime']
      //   const data = this.multipleSelection.map(v => filterVal.map(j => {
      //     switch (j) {
      //       case 'readFlag':
      //         return v[j] === 1 ? '已读' : '未读'
      //       default:return v[j]
      //     }
      //   }))
      //   excel.export_json_to_excel({
      //     header: tHeader,
      //     data,
      //     filename: '我的信息导出'
      //   })
      // })
    },
    // 列表序号
    table_index(index) {
      return (this.filterForm.pageNo - 1) * this.filterForm.pageSize + index + 1
    }
  }
}
</script>

<style lang="scss">
  .notice{
    .el-row{
      // margin: 20px;
      .el-col > .el-button {
        margin-left: 10px;
      }
    }
    .btns {
      margin-left: 37%;
    }
    .el-table{
       .true{
        display: none;
      }
    }
  }
</style>
